
// 创建用户相关的仓库
import { defineStore } from "pinia";
import { loginAPI } from "@/api/login";
import { reqLogout } from "@/api/user";
import { get_token, set_token, remove_token, set_userInfo, remove_userInfo } from "@/utils/token";

export const useUserStore = defineStore("user", {
    state: () => {
        return {
            token: get_token(),
            // 定义 token 的过期时间(秒)
            TimeOver: 1800,
            username: '',
            avatar: ''
        };
    },
    getters: {},
    actions: {
        async doLogin({ username, password }) {
            const result = await loginAPI({ username, password });
            if (result.data.status === 200) {
                this.token = result.data.data.token
                //本地存储
                set_token(result.data.data.token)
                set_userInfo({ username: result.data.data.username, avatar: result.data.data.avatar })
                this.username = result.data.data.username
                this.avatar = result.data.data.avatar
                return 'ok'
            } else {
                return Promise.reject(new Error(result.data.message))
            }
        },

        async userLogout() {
            // 退出登录
            const result = await reqLogout()
            if (result.code === 200) {
                remove_token()
                remove_userInfo()
                
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }

        },
        async getUserInfo() {

        }
    },
    persist: {
        enabled: true
    }

})
